﻿using Idenmpotency;
using Microsoft.AspNetCore.Idenmpotency;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// 扩展方法：用于暴露中间件注册、使用接口的类
    /// </summary>
    public static class IdenmpotencyServiceCollectionExtensions
    {
        /// <summary>
        /// 使用幂等性请求服务
        /// </summary>
        /// <param name="app"></param>
        /// <param name=""></param>
        /// <returns></returns>
        public static IApplicationBuilder UseIdenmpotency(this IApplicationBuilder appBuilder)
        {
            appBuilder.Use(async (context, next) => {
               var midllerware = new IdenmpotencyMidllerware(appBuilder, next);
               await midllerware.Invoke(context);
            });
            return appBuilder;
        }

        /// <summary>
        /// 添加幂等性请求服务
        /// </summary>
        /// <param name="services"></param>
        /// <param name="builderAction"></param>
        /// <returns></returns>
        public static IServiceCollection AddIdenmpotency(this IServiceCollection services,Action<AspIdenmpotencyBuilder> builderAction)
        {
            var builder = new AspIdenmpotencyBuilder(services);
            builderAction.Invoke(builder);
            if (!builder.IsBuilt)
            {
                throw new IdenmpotencyException($"Idenmpotency未建造，请检查Build方法是否被调用");
            }
            return services;
        }
    }
}
